package com.ruoyi.merchant.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.merchant.domain.Order;
import com.ruoyi.merchant.domain.dto.OrderCancelDTO;
import com.ruoyi.merchant.domain.dto.OrderQueryDTO;
import com.ruoyi.merchant.service.IOrderService;
import com.ruoyi.merchant.service.impl.OrderExportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 订单管理Controller
 */
@RestController
@RequestMapping("/merchant/order")
public class OrderController extends BaseController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private OrderExportService exportService;


    /**
     * 导出订单列表
     */
    @Log(title = "导出订单", businessType = BusinessType.EXPORT)
    @PostMapping("/orderExport")
    public void export(HttpServletResponse response, OrderQueryDTO queryDTO) {
        try {
            byte[] data = exportService.exportOrderList(queryDTO);

            String fileName = "订单列表_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xlsx";

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(fileName, "UTF-8"));

            response.getOutputStream().write(data);
            response.getOutputStream().flush();

        } catch (Exception e) {
            log.error("导出订单失败", e);
            throw new ServiceException("导出订单失败：" + e.getMessage());
        }
    }

    /**
     * 导出订单详情
     */
    @Log(title = "导出订单详情", businessType = BusinessType.EXPORT)
    @GetMapping("/export/{orderId}")
    public void exportDetail(HttpServletResponse response, @PathVariable Long orderId) {
        try {
            byte[] data = exportService.exportOrderDetail(orderId);

            String fileName = "订单详情_" + orderId + "_" +
                    new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xlsx";

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(fileName, "UTF-8"));

            response.getOutputStream().write(data);
            response.getOutputStream().flush();

        } catch (Exception e) {
            log.error("导出订单详情失败", e);
            throw new ServiceException("导出订单详情失败：" + e.getMessage());
        }
    }

    /**
     * 查询订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(OrderQueryDTO queryDTO) {
        startPage();
        List<Order> list = orderService.selectOrderList(queryDTO);
        return getDataTable(list);
    }

    /**
     * 获取订单详细信息
     */
    @GetMapping("/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId) {
        return success(orderService.selectOrderByOrderId(orderId));
    }

    /**
     * 订单统计（按状态）
     */
    @GetMapping("/statistics")
    public AjaxResult statistics() {
        return success(orderService.countOrderByStatus());
    }

    /**
     * 今日订单概览
     */
    @GetMapping("/today-summary")
    public AjaxResult todaySummary() {
        return success(orderService.getTodaySummary());
    }

    /**
     * 营业额统计
     */
    @GetMapping("/amount-statistics")
    public AjaxResult amountStatistics(
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        return success(orderService.getOrderAmountStatistics(startTime, endTime));
    }

    /**
     * 接单
     */
    @Log(title = "接单", businessType = BusinessType.UPDATE)
    @PutMapping("/accept/{orderId}")
    public AjaxResult accept(
            @PathVariable("orderId") Long orderId,
            @RequestParam(required = false, defaultValue = "15") Integer estimatedMin) {
        return toAjax(orderService.acceptOrder(orderId, estimatedMin));
    }

    /**
     * 批量接单
     */
    @Log(title = "批量接单", businessType = BusinessType.UPDATE)
    @PutMapping("/batch-accept")
    public AjaxResult batchAccept(@RequestBody Map<String, Object> params) {
        Long[] orderIds = ((List<Integer>) params.get("orderIds"))
                .stream()
                .map(Long::valueOf)
                .toArray(Long[]::new);
        Integer estimatedMin = (Integer) params.getOrDefault("estimatedMin", 15);
        return toAjax(orderService.batchAcceptOrders(orderIds, estimatedMin));
    }

    /**
     * 开始制作
     */
    @Log(title = "开始制作", businessType = BusinessType.UPDATE)
    @PutMapping("/start-making/{orderId}")
    public AjaxResult startMaking(@PathVariable("orderId") Long orderId) {
        return toAjax(orderService.startMaking(orderId));
    }

    /**
     * 制作完成（待取餐）
     */
    @Log(title = "制作完成", businessType = BusinessType.UPDATE)
    @PutMapping("/ready/{orderId}")
    public AjaxResult ready(@PathVariable("orderId") Long orderId) {
        return toAjax(orderService.orderReady(orderId));
    }

    /**
     * 完成订单
     */
    @Log(title = "完成订单", businessType = BusinessType.UPDATE)
    @PutMapping("/complete/{orderId}")
    public AjaxResult complete(@PathVariable("orderId") Long orderId) {
        return toAjax(orderService.completeOrder(orderId));
    }

    /**
     * 取消订单
     */
    @Log(title = "取消订单", businessType = BusinessType.UPDATE)
    @PutMapping("/cancel")
    public AjaxResult cancel(@Validated @RequestBody OrderCancelDTO cancelDTO) {
        return toAjax(orderService.cancelOrder(cancelDTO));
    }

    /**
     * 打印订单
     */
    @Log(title = "打印订单", businessType = BusinessType.OTHER)
    @PostMapping("/print/{orderId}")
    public AjaxResult print(
            @PathVariable("orderId") Long orderId,
            @RequestParam(required = false) Long printerId) {
        return toAjax(orderService.printOrder(orderId, printerId));
    }
}
